package org.giovanolli.mumi.service.impl;

import java.util.List;

import org.giovanolli.mumi.dao.Dao;
import org.giovanolli.mumi.dao.RoleDao;
import org.giovanolli.mumi.dao.UserDao;
import org.giovanolli.mumi.entities.filter.RoleFilter;
import org.giovanolli.mumi.entities.security.Role;
import org.giovanolli.mumi.entities.security.User;
import org.giovanolli.mumi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service("userService")
@Transactional(propagation = Propagation.SUPPORTS)
public class UserServiceImpl extends AbstractService<User> implements UserService {

	@Autowired
	private UserDao userDao;

	@Autowired
	private RoleDao roleDao;

	@Autowired
	private PasswordEncoder passwordEncoder;

	@Override
	@Transactional(readOnly = true)
	public List<Role> getAllRoles() {
		return roleDao.getList(new RoleFilter());
	}

	@Override
	protected Dao<User> getServiceDao() {
		return userDao;
	}

	@Override
	@Transactional(readOnly = true)
	public User getUserByUsername(String username) {
		return userDao.getUserByUsername(username);
	}

	/**
	 * Saves the user without encoding its password
	 * 
	 * @param entity
	 */
	@Override
	public void saveEntity(User entity) {
		saveUser(entity, false);
	}

	@Override
	@Transactional
	public void saveUser(User user, boolean encodePassword) {
		if (encodePassword) {
			final String encodedPassword = passwordEncoder.encodePassword(user.getPassword(), user.getUid());
			user.setPassword(encodedPassword);
		}
		userDao.save(user);
	}
}
